import 'dart:isolate';

import 'package:flutter/material.dart';
import 'package:flutter_ui_demo/res/button_styles.dart';

/// 多线程, 异步编程(防止main进程卡顿导致UI绘制卡顿)
class ComputOrIsolatePage extends StatefulWidget {
  ComputOrIsolatePage({Key? key}) : super(key: key);

  @override
  _ComputOrIsolatePageState createState() => _ComputOrIsolatePageState();
}

class _ComputOrIsolatePageState extends State<ComputOrIsolatePage> {
  int _count = 0;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('ComputOrIsolate'),
        centerTitle: true,
        elevation: 0.5,
      ),
      body: Material(
        child: Center(
          child: Column(
            children: <Widget>[
              Container(
                width: 100,
                height: 100,
                child: CircularProgressIndicator(),
              ),
              TextButton(
                style: flatButtonStyle,
                onPressed: () async {
                  // _count = countEven(1000000000);
                  // _count = await asyncCountEven(1000000000);
                  // _count = await compute(countEven, 1000000000);
                  _count = await isolateCountEven(1000000000);
                  print(_count);
                  setState(() {});
                },
                child: Text(
                  _count.toString(),
                ),
              ),
            ],
            mainAxisSize: MainAxisSize.min,
          ),
        ),
      ),
    );
  }

  //计算偶数的个数
  static int countEven(int num) {
    int count = 0;
    while (num > 0) {
      if (num % 2 == 0) {
        count++;
      }
      num--;
    }
    return count;
  }

  // static Future<int> asyncCountEven(int num) async {
  //   int count = 0;
  //   while (num > 0) {
  //     if (num % 2 == 0) {
  //       count++;
  //     }
  //     num--;
  //   }
  //   return count;
  // }

  static Future<dynamic> isolateCountEven(int num) async {
    final response = ReceivePort();
    await Isolate.spawn(countEvent2, response.sendPort);
    final sendPort = await response.first;
    final answer = ReceivePort();
    sendPort.send([answer.sendPort, num]);
    return answer.first;
  }

  static void countEvent2(SendPort port) {
    final rPort = ReceivePort();
    port.send(rPort.sendPort);
    rPort.listen((message) {
      final send = message[0] as SendPort;
      final n = message[1] as int;
      send.send(countEven(n));
    });
  }
}
